﻿using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace Smarly.Bussines
{
	public static class SmarlyCryptography
	{
		static SmarlyCryptography()
		{
			Passphrase = ConfigurationManager.AppSettings["SmarlySecret"] ?? "O4r4kww42z";
		}

		static readonly string Passphrase;

		public static string EncryptData(string message)
		{
			return Crypt((tdesAlgorithm, encoding) =>
			{
				byte[] dataToEncrypt = encoding.GetBytes(message);
				byte[] results = tdesAlgorithm.CreateEncryptor().TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
				return Convert.ToBase64String(results);

			});
		}

		public static string DecryptString(string message)
		{
			return Crypt((tdesAlgorithm, encoding) =>
			{
				byte[] dataToDecrypt = Convert.FromBase64String(message);
				byte[] results = tdesAlgorithm.CreateDecryptor().TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
				return encoding.GetString(results);
			});
		}

		private static string Crypt(Func<SymmetricAlgorithm, Encoding, string> func)
		{
			try
			{
				Encoding encoding = Encoding.UTF8;
				using (HashAlgorithm hashProvider = new MD5CryptoServiceProvider())
				{
					using (SymmetricAlgorithm tdesAlgorithm = new TripleDESCryptoServiceProvider
						                                          {
							                                          Key = hashProvider.ComputeHash(encoding.GetBytes(Passphrase)),
							                                          Mode = CipherMode.ECB,
							                                          Padding = PaddingMode.PKCS7
						                                          })
					{
						return func(tdesAlgorithm, encoding);
					}
				}
			}
			catch
			{
				return null;
			}
		}
	}
}